package com.victor9ac.tfm.rome2rio.api.adapter;

import org.jdom.Document;

import com.victor9ac.mashup.api.travel.Travel;
import com.victor9ac.mashup.port.TravelOperation;
import com.victor9ac.tfm.rome2rio.api.adapter.parse.Rome2RioSearchParse;
import com.victor9ac.tfm.rome2rio.api.connector.Rome2RioConnector;

public class Rome2RioTravelAdapter implements TravelOperation {

	
	Rome2RioConnector connector;
	
	
	
	Rome2RioSearchParse searchParse;
	
	public Travel getTravelFromTo(String from, String to) {
		
		Travel travel = new Travel();
		from = connector.setOrigin(from);
		
		if (checkDistintLocation(from, to)){
			travel = getTravel(to);
		}else{
			travel.setFrom(from);
			travel.setTo(to);
		}
		
		
		return travel;
	}



	public Travel getTravel(String destinationRequested) {

		Document doc = connect(destinationRequested);
		Travel travel = buildDomainResult(doc,destinationRequested);
		
		return travel;
	}

	private boolean checkDistintLocation(String from, String to) {
		return !(from.equalsIgnoreCase(to));
	}
	
	private Travel buildDomainResult(Document doc,String destination) {
		Travel travel = null;
		if (doc!=null){
			travel = searchParse.parseResponse(doc,connector.getOrigin(),destination);
		}
		return travel;
	}

	private Document connect(String dest) {
		Document doc = null;
		try {
			doc = connector.execute(dest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}

	public void setConnector(Rome2RioConnector connector) {
		this.connector = connector;
	}

	public void setSearchParse(Rome2RioSearchParse searchParse) {
		this.searchParse = searchParse;
	}

}
